package com.wangjiacai.utils.ali.tts;

import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import com.alibaba.nls.client.transport.ConnectionListener;
import com.wangjiacai.utils.ali.AliPool;
import com.wangjiacai.utils.ali.NettyConnection;
import com.wangjiacai.utils.ali.NettyNlsClient;
import com.wangjiacai.utils.ali.NettySpeechListener;

import java.nio.ByteBuffer;

public class AliTtsPool extends AliPool {

    private String appKey;

    public AliTtsPool(NettyNlsClient nettyNlsClient, String appKey, int maxSize){
        super(nettyNlsClient,maxSize);
        this.appKey = appKey;
    }

    @Override
    public NettyConnection getConnection(NettySpeechListener listener, ConnectionListener connectionListener) throws Exception {
        while (workSize.get()>= maxSize) {
            synchronized (waitNum) {
                waitNum.getAndIncrement();
                waitNum.wait();
                waitNum.getAndDecrement();
            }
        }
        NettyConnection nettyConnection = nettyNlsClient.connect(listener);
        nettyConnection.setAliPool(this);
        listener.setConnectionListener(connectionListener);
        return nettyConnection;
    }

    @Override
    public void free(NettyConnection nettyConnection) {
        synchronized (waitNum){
            nettyConnection.getChannel().close();
            waitNum.notify();
        }
    }

    public NettyConnection getConnection(ConnectionListener connectionListener) throws Exception {
        NettyConnection nettyConnection=getConnection(getNettySpeechSynthesizerListener(),connectionListener);
        nettyConnection.setAppKey(appKey);
        return nettyConnection;
    }

    private NettySpeechSynthesizerListener getNettySpeechSynthesizerListener(){
        return new NettySpeechSynthesizerListener(){
            @Override
            public void onComplete(SpeechSynthesizerResponse speechSynthesizerResponse) {
                this.getNettyConnection().close();
                if(this.getConnectionListener() instanceof SpeechSynthesizerListener){
                    SpeechSynthesizerListener speechSynthesizerListener= (SpeechSynthesizerListener) this.getConnectionListener();
                    speechSynthesizerListener.onComplete(speechSynthesizerResponse);
                }
            }
            @Override
            public void onMessage(ByteBuffer message) {
                this.getConnectionListener().onMessage(message);
            }
        };
    }

}
